Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Python Functions → Passing function as an argument

Python Functions

Passing function as an argument

In Python, functions are first-class citizens. This means they can be treated like any other object: assigned to variables, passed as arguments to other functions, and returned as values from functions. This capability significantly enhances code reusability and flexibility. Let's explore this concept with detailed examples.

Core Idea

When you pass a function as an argument, you're essentially passing a reference to that function's code. The receiving function can then *call* the passed-in function, executing its logic within its own context.

Example 1: Basic Function Passing

Let's create a simple function that takes another function as an argument and then calls it:
Basic Function Passing example in python def apply_function(func, value): """Applies a function to a given value and returns the result.""" return func(value) def square(x): """Squares a number.""" return x * x def cube(x): """Cubes a number.""" return x * x * x # Pass 'square' and 'cube' functions to 'apply_function' result1 = apply_function(square, 5) result2 = apply_function(cube, 5) print(f"Square of 5: {result1}") print(f"Cube of 5: {result2}")

Output

Square of 5: 25 Cube of 5: 125
Here, `apply_function` is a higher-order function (a function that takes another function as an argument or returns a function). We pass `square` and `cube` as arguments, and `apply_function` executes them with the provided value.

Example 2: Customizing Behavior with Function Arguments

We can enhance flexibility by allowing the caller to pass additional arguments to the function being passed:
Customizing Behavior with Function Arguments def apply_function_with_args(func, value, *args, **kwargs): """Applies a function to a value, handling additional arguments.""" return func(value, *args, **kwargs) def greet(name, greeting="Hello"): """Greets a person.""" return f"{greeting}, {name}!" # Pass 'greet' with additional arguments result = apply_function_with_args(greet, "Alice", greeting="Good morning") print(result) result = apply_function_with_args(greet, "Bob") print(result)

Output

Good morning, Alice! Hello, Bob!
`*args` and `**kwargs` allow us to handle a variable number of positional and keyword arguments, respectively, which are then passed on to the function called inside `apply_function_with_args`.

Example 3: Function as a Return Value

Functions can also return other functions:
Function as a Return Value def create_multiplier(factor): """Creates a function that multiplies a number by a given factor.""" def multiplier(x): return x * factor return multiplier double = create_multiplier(2) # double is now a function that multiplies by 2 triple = create_multiplier(3) # triple is now a function that multiplies by 3 print(f"Double of 5: {double(5)}") print(f"Triple of 5: {triple(5)}")

Output

Double of 5: 10 Triple of 5: 15
`create_multiplier` returns a closure – a function that "remembers" the value of `factor` from its enclosing scope, even after `create_multiplier` has finished executing.

Example 4: Callbacks and Event Handling

A common use case is in event handling or callbacks:
Callbacks and Event Handling while passing function as argument def process_event(event_type, callback): """Processes an event and calls a callback function.""" print(f"Event triggered: {event_type}") callback() def on_success(): print("Success!") def on_error(): print("Error!") process_event("Login success", on_success) process_event("File not found", on_error)

Output

Event triggered: Login success Success! Event triggered: File not found Error!
Here, `process_event` takes a callback function (`on_success` or `on_error`) which is executed depending on the event type.

Tutorials